<?php

namespace App\Observers;

use App\Models\User;
use App\Models\IntegralRule;
use App\Notifications\IntegralChange;
use Illuminate\Support\Carbon;
use Ip2Region;
class UserObserver
{
    /**
     * Handle the user "created" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function created(User $user)
    {
        //注册赠卡券
//        如果不是通过扫码注册的，则送积分
        if($user->come_from !=2){
            //注册赠积分
            $integral = IntegralRule::getRegisterIntegral();
            $user->userIntegral()->create([
                "integral"=>0,
            ]);
            //积分历史记录增加一笔
            $user->userIntegralLogs()->create([
                "integral"=>$integral,
                "des"=>"注册赠送积分",
                "is_checked"=>true,// 由于是系统自动发放，所以已审核
                "is_added"=>true,//已发送过积分
            ]);
            //发送积分赠送通知
            $notification['user_id'] = $user->id;
            $notification['title'] = "注册赠送积分已到帐，快到积分商城看看吧！";
            $user->couponNotify(new IntegralChange($notification));
        }else{
            //如果是扫码注册的话，加入成交年
            $user->deal_time = Carbon::now()->year;
            $user->save();
            $user->userIntegral()->create([
                "integral"=>0,
            ]);
        }
        //自动设定注册地ip所在的城市
        $user->setUserRegisterCity();
    }

    /**
     * Handle the user "updated" event.
     *用户注册，进行礼品券的发放
     * @param  \App\User  $user
     * @return void
     */
    public function updated(User $user)
    {
    }

    /**
     * Handle the user "deleted" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function deleted(User $user)
    {
        //
    }

    /**
     * Handle the user "restored" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function restored(User $user)
    {
        //
    }

    /**
     * Handle the user "force deleted" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function forceDeleted(User $user)
    {
        $user->sinInLogs()->delete();
        $user->collectionGoods()->delete();
        $user->coupons()->delete();
        $user->userIntegral()->delete();
        $user->userIntegralLogs()->delete();
        $user->userVisitLogs()->delete();
        $user->userAskForGoods()->delete();
    }
}
